package com.hejia.alauda.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.util.Calendar;
import java.util.Date;

public class HolidayUtil {


    public static HolidayUtil instance(){
        return new HolidayUtil();
    }

	/**
	 * 判断结息日是否节假日
	 * 
	 * @param sDate 起息日
	 * @param term 期限
	 * @return true false
	 */
	public boolean isHoliday(String sDate, int term) {

		if (sDate == null || term <= 0) {
			return false;
		}

		try {
			Date date = DateFormatUtils.ISO_DATE_FORMAT.parse(sDate.substring(
					0, 10));
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.add(Calendar.DATE, term);
			int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
			if (dayOfWeek == 1 || dayOfWeek == 7) {
				return true;
			}

            Date date1 = calendar.getTime();
			CloseableHttpClient httpclient = HttpClients.createDefault();
			String day = DateFormatUtils.format(calendar, "yyyyMMdd");
			HttpGet httpGet = new HttpGet(
					"http://www.easybots.cn/api/holiday.php?d=" + day);
			CloseableHttpResponse response1 = httpclient.execute(httpGet);
			HttpEntity entity1 = response1.getEntity();
			if (entity1 != null) {
				String response = EntityUtils.toString(entity1, "UTF-8");
				JSONObject jsonResp = JSONObject.parseObject(response);
				if (((Integer) jsonResp.get(day)).intValue() != 0) {
					return true;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

}
